import { PlayerEntity, PlayerLevel } from '../domain/entity/PlayerEntity';
import { PlayerAggregate, PlayerStatistics } from '../domain/aggregate/PlayerAggregate';
import { PlayerRepository, PlayerRepositoryImpl } from '../repository/PlayerRepository';

// 玩家应用服务层 - 协调领域层和数据访问层
export class PlayerAppService {
  private playerRepository: PlayerRepository;
  private static instance: PlayerAppService;
  
  private constructor() {
    this.playerRepository = new PlayerRepositoryImpl();
  }
  
  // 获取单例实例
  public static getInstance(): PlayerAppService {
    if (!PlayerAppService.instance) {
      PlayerAppService.instance = new PlayerAppService();
    }
    return PlayerAppService.instance;
  }
  
  // 注册新玩家
  async registerPlayer(
    username: string,
    nickname: string,
    avatarUrl?: string
  ): Promise<PlayerEntity | null> {
    try {
      // 检查用户名是否已存在
      const existingPlayer = await this.playerRepository.getPlayerByUsername(username);
      if (existingPlayer) {
        console.warn('Username already exists:', username);
        return null;
      }
      
      // 创建新玩家
      const newPlayer = new PlayerEntity(
        Date.now().toString(),
        username,
        nickname,
        avatarUrl
      );
      
      // 保存玩家
      const success = await this.playerRepository.savePlayer(newPlayer);
      return success ? newPlayer : null;
    } catch (error) {
      console.error('Failed to register player:', error);
      return null;
    }
  }
  
  // 获取玩家信息
  async getPlayerById(id: string): Promise<PlayerAggregate | null> {
    try {
      const player = await this.playerRepository.getPlayerById(id);
      if (!player) {
        return null;
      }
      
      const achievements = await this.playerRepository.getPlayerAchievements(id);
      return new PlayerAggregate(player, achievements);
    } catch (error) {
      console.error(`Failed to get player ${id}:`, error);
      return null;
    }
  }
  
  // 玩家登录
  async loginPlayer(username: string): Promise<PlayerEntity | null> {
    try {
      const player = await this.playerRepository.getPlayerByUsername(username);
      if (!player) {
        return null;
      }
      
      // 更新登录时间
      player.updateLoginTime();
      await this.playerRepository.updatePlayer(player);
      
      return player;
    } catch (error) {
      console.error(`Failed to login player ${username}:`, error);
      return null;
    }
  }
  
  // 更新玩家信息
  async updatePlayerInfo(
    playerId: string,
    updates: Partial<Pick<PlayerEntity, 'nickname' | 'avatarUrl'>>
  ): Promise<boolean> {
    try {
      const player = await this.playerRepository.getPlayerById(playerId);
      if (!player) {
        return false;
      }
      
      // 应用更新
      if (updates.nickname) player.nickname = updates.nickname;
      if (updates.avatarUrl) player.avatarUrl = updates.avatarUrl;
      
      return await this.playerRepository.updatePlayer(player);
    } catch (error) {
      console.error(`Failed to update player ${playerId}:`, error);
      return false;
    }
  }
  
  // 更新玩家偏好设置
  async updatePlayerPreferences(
    playerId: string,
    preferences: Partial<PlayerEntity['preferences']>
  ): Promise<boolean> {
    try {
      const playerAggregate = await this.getPlayerById(playerId);
      if (!playerAggregate) {
        return false;
      }
      
      // 更新偏好设置
      playerAggregate.updatePreferences(preferences);
      
      return await this.playerRepository.updatePlayer(playerAggregate.playerEntity);
    } catch (error) {
      console.error(`Failed to update preferences for player ${playerId}:`, error);
      return false;
    }
  }
  
  // 玩家完成案件
  async completeCase(
    playerId: string,
    caseId: string,
    correct: boolean,
    caseDifficulty: number,
    timeTaken: number,
    isFirstAttempt: boolean
  ): Promise<PlayerStatistics | null> {
    try {
      const playerAggregate = await this.getPlayerById(playerId);
      if (!playerAggregate) {
        return null;
      }
      
      // 处理案件完成逻辑
      playerAggregate.completeCase(
        caseId,
        correct,
        caseDifficulty,
        timeTaken,
        isFirstAttempt
      );
      
      // 保存更新后的玩家信息
      await this.playerRepository.updatePlayer(playerAggregate.playerEntity);
      await this.playerRepository.savePlayerAchievements(
        playerId,
        playerAggregate.achievements
      );
      
      // 返回最新统计信息
      return playerAggregate.getStatistics();
    } catch (error) {
      console.error(`Failed to process case completion for player ${playerId}:`, error);
      return null;
    }
  }
  
  // 获取玩家排行榜
  async getPlayerLeaderboard(limit: number = 10): Promise<Array<{player: PlayerEntity, rank: number}>> {
    try {
      const allPlayers = await this.playerRepository.getAllPlayers();
      
      // 按解决案件数量和准确率排序
      const sortedPlayers = allPlayers.sort((a, b) => {
        if (b.solvedCases !== a.solvedCases) {
          return b.solvedCases - a.solvedCases;
        }
        return b.accuracy - a.accuracy;
      });
      
      // 返回前N名并添加排名
      return sortedPlayers.slice(0, limit).map((player, index) => ({
        player,
        rank: index + 1
      }));
    } catch (error) {
      console.error('Failed to get player leaderboard:', error);
      return [];
    }
  }
}
